<template>
  <div class="dashboard-container">
    <el-row :gutter="20">
      <el-col :span="24">
        <div class="welcome-banner">
          <h2>欢迎回来，{{ user?.full_name || user?.username }}</h2>
          <p>今天是 {{ currentDate }}</p>
        </div>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="dashboard-stats">
      <el-col :xs="24" :sm="12" :md="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-value">{{ projectsCount }}</div>
          <div class="stat-label">我的项目</div>
        </el-card>
      </el-col>
      
      <el-col :xs="24" :sm="12" :md="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-value">{{ tasksCount }}</div>
          <div class="stat-label">待办任务</div>
        </el-card>
      </el-col>
      
      <el-col :xs="24" :sm="12" :md="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-value">{{ risksCount }}</div>
          <div class="stat-label">风险项</div>
        </el-card>
      </el-col>
      
      <el-col :xs="24" :sm="12" :md="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-value">{{ notificationsCount }}</div>
          <div class="stat-label">未读通知</div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20">
      <el-col :xs="24" :md="16">
        <el-card class="recent-projects-card">
          <template #header>
            <div class="card-header">
              <h3>最近的项目</h3>
              <el-button type="primary" size="small" @click="goToProjects">查看全部</el-button>
            </div>
          </template>
          
          <el-table :data="recentProjects" style="width: 100%" v-loading="loading">
            <el-table-column prop="name" label="项目名称">
              <template #default="{row}">
                <router-link :to="`/projects/${row.id}`">{{ row.name }}</router-link>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态">
              <template #default="{row}">
                <el-tag :type="getStatusType(row.status)">{{ row.status }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="progress" label="进度">
              <template #default="{row}">
                <el-progress :percentage="row.progress || 0" :status="getProgressStatus(row.progress)"></el-progress>
              </template>
            </el-table-column>
            <el-table-column prop="end_date" label="截止日期"></el-table-column>
          </el-table>
        </el-card>
      </el-col>
      
      <el-col :xs="24" :md="8">
        <el-card class="notifications-card">
          <template #header>
            <div class="card-header">
              <h3>最新通知</h3>
              <el-button type="text" @click="markAllAsRead" :disabled="!notifications.length">全部标为已读</el-button>
            </div>
          </template>
          
          <div v-if="notifications.length" class="notifications-list">
            <div v-for="notification in notifications" :key="notification.id" class="notification-item">
              <div class="notification-content">
                <div class="notification-title">{{ notification.title }}</div>
                <div class="notification-message">{{ notification.message }}</div>
                <div class="notification-time">{{ formatTime(notification.created_at) }}</div>
              </div>
              <el-button 
                type="text" 
                size="small" 
                @click="markAsRead(notification.id)"
                v-if="!notification.is_read"
              >标为已读</el-button>
            </div>
          </div>
          
          <el-empty v-else description="暂无通知"></el-empty>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20">
      <el-col :span="24">
        <el-card class="upcoming-tasks-card">
          <template #header>
            <div class="card-header">
              <h3>即将到期的任务</h3>
              <el-button type="primary" size="small" @click="goToTasks">查看全部</el-button>
            </div>
          </template>
          
          <el-table :data="upcomingTasks" style="width: 100%" v-loading="loading">
            <el-table-column prop="title" label="任务名称">
              <template #default="{row}">
                <router-link :to="`/tasks/${row.id}`">{{ row.title }}</router-link>
              </template>
            </el-table-column>
            <el-table-column prop="project.name" label="所属项目"></el-table-column>
            <el-table-column prop="status" label="状态">
              <template #default="{row}">
                <el-tag :type="getTaskStatusType(row.status)">{{ row.status }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="priority" label="优先级">
              <template #default="{row}">
                <el-tag :type="getPriorityType(row.priority)">{{ row.priority }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="due_date" label="截止日期"></el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'

export default {
  name: 'DashboardView',
  setup() {
    const store = useStore()
    const router = useRouter()
    const loading = ref(false)
    
    // 获取当前日期
    const currentDate = new Date().toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: 'long',
      day: 'numeric',
      weekday: 'long'
    })
    
    // 获取用户信息
    const user = computed(() => store.state.user)
    
    // 统计数据
    const projectsCount = ref(0)
    const tasksCount = ref(0)
    const risksCount = ref(0)
    const notificationsCount = ref(0)
    
    // 最近的项目
    const recentProjects = ref([])
    
    // 即将到期的任务
    const upcomingTasks = ref([])
    
    // 通知
    const notifications = ref([])
    
    // 获取数据
    const fetchDashboardData = async () => {
      loading.value = true
      try {
        // 获取项目列表
        const projects = await store.dispatch('fetchProjects')
        recentProjects.value = projects.slice(0, 5)
        projectsCount.value = projects.length
        
        // 获取任务列表
        const tasks = await store.dispatch('fetchTasks')
        upcomingTasks.value = tasks
          .filter(task => task.status !== 'COMPLETED')
          .sort((a, b) => new Date(a.due_date) - new Date(b.due_date))
          .slice(0, 5)
        tasksCount.value = tasks.filter(task => task.status !== 'COMPLETED').length
        
        // 获取通知
        const notifs = await store.dispatch('fetchNotifications')
        notifications.value = notifs.slice(0, 5)
        notificationsCount.value = notifs.filter(n => !n.is_read).length
        
        // 模拟风险数据
        risksCount.value = Math.floor(Math.random() * 5)
      } catch (error) {
        ElMessage.error('获取数据失败')
        console.error(error)
      } finally {
        loading.value = false
      }
    }
    
    // 标记通知为已读
    const markAsRead = async (id) => {
      try {
        await store.dispatch('markNotificationAsRead', id)
        notifications.value = notifications.value.map(n => {
          if (n.id === id) {
            return { ...n, is_read: true }
          }
          return n
        })
        notificationsCount.value = Math.max(0, notificationsCount.value - 1)
        ElMessage.success('已标记为已读')
      } catch (error) {
        ElMessage.error('操作失败')
      }
    }
    
    // 标记所有通知为已读
    const markAllAsRead = () => {
      // 实际项目中应调用API
      notifications.value = notifications.value.map(n => ({ ...n, is_read: true }))
      notificationsCount.value = 0
      ElMessage.success('已全部标记为已读')
    }
    
    // 格式化时间
    const formatTime = (timestamp) => {
      if (!timestamp) return ''
      const date = new Date(timestamp)
      return date.toLocaleString('zh-CN')
    }
    
    // 获取状态类型
    const getStatusType = (status) => {
      const statusMap = {
        'NOT_STARTED': 'info',
        'IN_PROGRESS': 'primary',
        'COMPLETED': 'success',
        'DELAYED': 'warning',
        'CANCELLED': 'danger'
      }
      return statusMap[status] || 'info'
    }
    
    // 获取任务状态类型
    const getTaskStatusType = (status) => {
      const statusMap = {
        'NOT_STARTED': 'info',
        'IN_PROGRESS': 'primary',
        'COMPLETED': 'success',
        'DELAYED': 'warning',
        'BLOCKED': 'danger'
      }
      return statusMap[status] || 'info'
    }
    
    // 获取优先级类型
    const getPriorityType = (priority) => {
      const priorityMap = {
        'LOW': 'info',
        'MEDIUM': 'warning',
        'HIGH': 'danger'
      }
      return priorityMap[priority] || 'info'
    }
    
    // 获取进度状态
    const getProgressStatus = (progress) => {
      if (progress >= 100) return 'success'
      if (progress >= 80) return 'warning'
      return ''
    }
    
    // 导航
    const goToProjects = () => router.push('/projects')
    const goToTasks = () => router.push('/tasks')
    
    onMounted(() => {
      fetchDashboardData()
    })
    
    return {
      currentDate,
      user,
      loading,
      projectsCount,
      tasksCount,
      risksCount,
      notificationsCount,
      recentProjects,
      upcomingTasks,
      notifications,
      markAsRead,
      markAllAsRead,
      formatTime,
      getStatusType,
      getTaskStatusType,
      getPriorityType,
      getProgressStatus,
      goToProjects,
      goToTasks
    }
  }
}
</script>

<style scoped>
.dashboard-container {
  padding: 20px;
}

.welcome-banner {
  background: linear-gradient(135deg, #409EFF 0%, #007BFF 100%);
  color: white;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.welcome-banner h2 {
  margin: 0;
  font-size: 24px;
}

.welcome-banner p {
  margin: 5px 0 0;
  opacity: 0.8;
}

.dashboard-stats {
  margin-bottom: 20px;
}

.stat-card {
  text-align: center;
  padding: 20px;
  margin-bottom: 20px;
}

.stat-value {
  font-size: 36px;
  font-weight: bold;
  color: #409EFF;
}

.stat-label {
  font-size: 14px;
  color: #606266;
  margin-top: 10px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  font-size: 18px;
}

.recent-projects-card,
.upcoming-tasks-card,
.notifications-card {
  margin-bottom: 20px;
}

.notifications-list {
  max-height: 400px;
  overflow-y: auto;
}

.notification-item {
  padding: 10px 0;
  border-bottom: 1px solid #EBEEF5;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.notification-item:last-child {
  border-bottom: none;
}

.notification-title {
  font-weight: bold;
  margin-bottom: 5px;
}

.notification-message {
  font-size: 14px;
  color: #606266;
  margin-bottom: 5px;
}

.notification-time {
  font-size: 12px;
  color: #909399;
}
</style>